<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            /*             var dailyTemperatures = function (temperatures) {
                let result = new Array(temperatures.length).fill(0)
                for (let i = 0; i < temperatures.length; i++) {
                    for (let j = i + 1; j < temperatures.length; j++) {
                        if (temperatures[j] > temperatures[i]) {
                            result[i] = i - j
                            break
                        }
                    }
                }
                return result
            } */
            var dailyTemperatures = function (temperatures) {
                let result = new Array(temperatures.length).fill(0)
                let stack = [0]
                /* 
                栈里先存放下标为0的，我们要确保一个单调递减栈，因为要求第一个大于它的元素
                如果当前元素小于栈顶元素，那么就入栈
                如果当前元素大于栈顶元素，计算距离，循环出栈,最后再把i入栈
                
                */
                for (let i = 1; i < temperatures.length; i++) {
                    let top = stack[stack.length - 1]
                    while (temperatures[i] > temperatures[top] && stack.length) {
                        result[top] = i - top
                        stack.pop()
                        top = stack[stack.length - 1]
                    }
                    stack.push(i)
                }
                return result
            }
            console.log(dailyTemperatures([73, 74, 75, 71, 69, 72, 76, 73]))
        </script>
    </body>
</html>
